<script lang="ts" setup>
import { formatNumber } from "@@/utils/tools/tools";
import { apiPhoneTopUpGoods, PhoneTopUpGoods } from "@@/api/page/phoneTopUp";
import { apiPhoneTopUpTxid } from "@@apiModule/transaction";
import { sdkTransferToken } from "@@/sdk/web3Eth";
import * as tronWeb from "@@/sdk/tronWeb";
import { isPhone } from "@@/utils/tools/is";
import toast from "@@/hooks/toast";
import useBalanceStore from "@@/store/useBalanceStore";
import useUserinfoStore from "@@/store/useUserinfoStore";
import useSysStore from "@@/store/useSysStore";
import dayjs from "dayjs";
const route = useRoute();
const query = route.query;

const sysStore = useSysStore();
const { lastLoginInfo } = storeToRefs(sysStore);
const userinfoStore = useUserinfoStore();
const { baseData } = storeToRefs(userinfoStore);
const balanceStore = useBalanceStore();
const { USDT } = storeToRefs(balanceStore);
const { t } = useI18n();
/** 充值套餐列表 */
const goodsList = reactive<PhoneTopUpGoods.ResItem[]>([]);
getGoodsList();
/**获取充值套餐列表 */
async function getGoodsList() {
  const res = await apiPhoneTopUpGoods();
  if (!res) return;
  goodsList.length = 0;
  goodsList.push(...res);
}
/**检查是否可以充值 */
function checkTopUpPhone(): boolean {
  console.log(lastLoginInfo.value?.accounts);
  let lastTopUpTime = window.localStorage.getItem(
    lastLoginInfo.value?.accounts + "TopUp"
  );
  //*第一次充值
  if (!lastTopUpTime) return true;
  const usableTime = dayjs(lastTopUpTime).add(1, "M");
  console.log(usableTime.format("YYYY-MM-DD HH:mm:ss"));
  const isAfter = dayjs().isAfter(usableTime);
  if (!isAfter) {
    toast.text(`${t("ning-dang-yue-yi-jing-chong-zhi-guo")}`);
  }
  return isAfter;
}
async function onSubmitBtn(item: PhoneTopUpGoods.ResItem) {
  const phone = formData.phone;
  if (!isPhone(phone))
    return toast.text(t("qing-shu-ru-zhen-que-de-shou-ji-hao"));
  const amount = item.usdt;
  if (!checkTopUpPhone()) return;
  console.log(item);
  if (await sysStore.isBab()) return transferEth(item, phone, amount);
  transferTron(item, phone, amount);
}
/**
 * 转账波场
 * @param item 商品
 * @param phone 手机号
 * @param amount 金额
 */
async function transferTron(
  item: PhoneTopUpGoods.ResItem,
  phone: string,
  amount: number
) {
  toast.loading();
  const res = await tronWeb.sdkTransferToken(
    "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
    amount,
    6,
    baseData.value?.trx_vip_address!
  );
  toast.close();
  if (!res.status) return toast.error(res.message || res.info || "fail");
  await apiPhoneTopUpTxid({
    txid: res.data!,
    product_id: item.id,
    mobile: phone,
    chain: 0,
  });
  //* 储存上次充值的时间
  window.localStorage.setItem(
    lastLoginInfo.value?.accounts + "TopUp",
    dayjs().format("YYYY-MM-DD HH:mm:ss")
  );
}
/**
 * 转账以太坊
 * @param item 商品
 * @param phone 手机号
 * @param amount 金额
 */
async function transferEth(
  item: PhoneTopUpGoods.ResItem,
  phone: string,
  amount: number
) {
  const usdtCoin = USDT.value!;
  toast.loading();
  const res = await sdkTransferToken(
    usdtCoin.contract_addr!,
    amount,
    usdtCoin.format,
    baseData.value?.address!
  );
  toast.close();
  if (!res.status) return toast.error(res.message || res.info || "fail");
  await apiPhoneTopUpTxid({
    txid: res.data!,
    product_id: item.id,
    mobile: phone,
    chain: 56,
  });
  //* 储存上次充值的时间
  window.localStorage.setItem(
    lastLoginInfo.value?.accounts + "TopUp",
    dayjs().format("YYYY-MM-DD HH:mm:ss")
  );
}
/**表单数据 */
const formData = reactive({
  phone: "",
  type: query.type || "0",
});
</script>

<template>
  <Ccard>
    <template #header>
      <div class="auto-mt-sm">
        <h3>{{ $t("qing-shu-ru-shou-ji-hao-ma") }}</h3>
        <RradioBtnGroup v-model="formData.type">
          <RradioBtn value="0">
            <template #default="{ checked }">
              <div :style="{ color: checked ? 'var(--C-B2)' : '' }">
                {{ $t("zhong-guo-dian-xin") }}
              </div>
            </template>
          </RradioBtn>
          <RradioBtn value="1">
            <template #default="{ checked }">
              <div :style="{ color: checked ? 'var(--C-B2)' : '' }">
                {{ $t("zhong-guo-lian-tong") }}
              </div>
            </template>
          </RradioBtn>
          <RradioBtn value="2">
            <template #default="{ checked }">
              <div :style="{ color: checked ? 'var(--C-B2)' : '' }">
                {{ $t("zhong-guo-yi-dong") }}
              </div>
            </template>
          </RradioBtn>
        </RradioBtnGroup>
        <van-field
          maxlength="11"
          v-model="formData.phone"
          type="tel"
          :placeholder="$t('qing-shu-ru-shou-ji-hao-ma')"
        />
      </div>
    </template>
    <div class="auto-mt-md">
      <h3>{{ $t("hua-fei-chong-zhi") }}</h3>
      <div class="selectTopUp gridVar--col" style="--col: 2">
        <div
          @click="onSubmitBtn(goods)"
          v-for="goods in goodsList"
          :key="goods.id"
          class="selectTopUp_item active auto-mt-md"
        >
          <h3>{{ formatNumber(goods.price * 0.9) }}RMB</h3>
          <div>
            {{ $t("yue-dao-zhang") }}:{{ formatNumber(goods.price) }}CNY
          </div>
          <div>{{ formatNumber(goods.usdt) }}USDT</div>
          <div class="selectTopUp_item_badge">{{ $t("9-zhe") }}</div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="auto-mt-xs T-S-sm">
        <h3>{{ $t("chong-zhi-xu-zhi") }}</h3>
        <div class="T-strong C-fail">
          {{
            $t(
              "qing-zi-xi-he-dui-chong-zhi-hao-ma-hao-ma-cuo-wu-chong-zhi-cheng-gong-wu-fa-tui-kuan"
            )
          }}
        </div>
        <div>
          {{
            $t(
              "1-hua-fei-kuai-chong-ri-chang-05-xiao-shi-nei-dao-zhang-yue-chu-yue-mo-gao-feng-qi-2-xiao-shi-nei-dao-zhang-zui-chi-bu-chao-guo-24-xiao-shi-dao-zhang-yi-ge-ha-xi-di-zhi-25-tian-nei-xian-zhi-chong-zhi-yi-ci-hua-fei-chao-shi-wei-dao-zhang-quanetui-kuan-bu-zhi-chi-cui-dan-ji-yong-wu-xia-dan"
            )
          }}
        </div>
        <div>
          {{
            $t(
              "2-xia-dan-hou-xi-tong-hui-zi-dong-ti-jiao-chong-zhi-chong-zhi-guo-cheng-zhong-qing-wu-zai-qi-ta-ping-tai-chong-zhi-xiang-tong-mian-zhi-ren-gong-wu-fa-gan-yu-tui-kuan-huo-geng-gai-hao-ma-qing-nin-zi-xi-he-dui-chong-zhi-hao-ma-kong-hao-cuo-hao-deng-ye-hui-chong-zhi-cheng-gong-chong-cuo-hao-ma-gai-bu-fu-ze"
            )
          }}
        </div>
        <div>
          {{
            $t(
              "3-fu-ka-kong-hao-xie-hao-zhuan-wang-xu-ni-hao-duan-yun-ying-shang-hei-ming-dan-deng-te-shu-hao-ma-wu-fa-chong-zhi-qing-wu-ti-jiao"
            )
          }}
        </div>
        <div>
          {{ $t("4-hua-fei-kuai-chong-man-chong-jun-bu-zhi-chi-kai-fa-piao") }}
        </div>
        <div>
          {{
            $t(
              "5-hua-fei-kuai-chong-man-chong-zhe-kou-ke-neng-sui-shi-bian-hua-ju-ti-yi-fu-kuan-shi-xian-shi-de-jia-ge-wei-zhun"
            )
          }}
        </div>
        <div>
          {{
            $t("yi-jian-ji-jian-yi-ti-yi-fan-kui-qing-you-jian-lian-xi-wo-men")
          }}
          <div>
            {{ $t("guan-fangemail") }}
            <CcopyText class="CcopyText" copy-text="bobbichain@126.com">
              bobbichain@126.com
            </CcopyText>
          </div>
        </div>
      </div>
    </template>
  </Ccard>
</template>

<style lang="less" scoped>
.selectTopUp {
  gap: var(--gap-md);
  .selectTopUp_item {
    position: relative;
    border: var(--C-OT5) solid 1rem;
    border-radius: var(--R-sm);
    text-align: center;
    width: 100%;
    font-size: var(--T-S-sm);
    padding: var(--gap-md);
    background-color: var(--C-B1);
    .selectTopUp_item_badge {
      position: absolute;
      left: 0;
      top: 0;
      margin: auto;
      transform: translateY(-50%);
      background-color: var(--C-M1);
      color: var(--C-B2);
      border-radius: var(--R-sm);
      padding: 0 0.5em;
    }
  }
}
.CcopyText {
  display: inline;
  text-decoration: underline;
}
</style>
